from datetime import datetime
from typing import Optional

from sqlalchemy.orm import declared_attr
from sqlmodel import SQLModel as _SQLModel, Field


def encode_datetime(d: datetime) -> str:
    # 自定义 datetime 编码函数
    return d.strftime("%Y-%m-%d %H:%M:%S") if d else None


class SQLModel(_SQLModel):
    @declared_attr  # type: ignore
    def __tablename__(cls) -> str:
        return cls.__name__

    def update(self, data):
        """
        通过字典 批量更新字段
        """
        for key, value in data.items():
            if hasattr(self, key):
                setattr(self, key, value)

    class Config:
        from_attributes = True
        str_strip_whitespace = True

        """Define a custom encoder for Sets such that they are sorted lists."""
        json_encoders = {
            datetime: encode_datetime,  # 使用我们自定义的 datetime 编码器
        }


class BaseModel(SQLModel):
    id: Optional[int] = Field(default=None,  primary_key=True)
    create_time: datetime = Field(
        default_factory=datetime.now,
        nullable=False,
    )
    update_time: datetime = Field(
        default_factory=datetime.now,
        nullable=False,
        sa_column_kwargs={
            "onupdate": datetime.now,
        }
    )
